package leetcode;

/**
 * 21.合并两个有序链表
 * <p>
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
 * <p>
 *  
 * <p>
 * 示例：
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 *
 * @author: cuihao
 * @create: 2020-07-01 23:11
 **/
public class MergeTwoLists {

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {

        // 异常情况
        if (list1 == null && list2 == null) {
            return null;
        }
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        // 哑结点
        ListNode head = new ListNode();
        ListNode node = head;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                node.next = list1;
                list1 = list1.next;
                node = node.next;
            } else if (list1.val > list2.val) {
                node.next = list2;
                list2 = list2.next;
                node = node.next;
            } else {
                node.next = list1;
                list1 = list1.next;
                node = node.next;

                node.next = list2;
                list2 = list2.next;
                node = node.next;
            }
        }

        while (list1 != null) {
            node.next = list1;
            list1 = list1.next;
            node = node.next;
        }
        while (list2 != null) {
            node.next = list2;
            list2 = list2.next;
            node = node.next;
        }

        return head.next;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(1, new ListNode(2, new ListNode(4)));

        ListNode node1 = new ListNode(1, new ListNode(3, new ListNode(4)));

        mergeTwoLists(node, node1);
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
